package com.agileai.wm.module.system.exteral;

import java.util.Date;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.apache.commons.codec.binary.Base64;
import com.agileai.common.AppConfig;
import com.agileai.common.KeyGenerator;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.cache.CacheService;
import com.agileai.hotweb.common.BeanFactory;
import com.agileai.hotweb.ws.BaseRestService;
import com.agileai.util.CryptionUtil;
import com.agileai.util.StringUtil;
import com.agileai.wm.model.Token;

public class ApiAuthenticaterImpl extends BaseRestService
	implements ApiAuthenticater{
	
	@Override
	public Response authticate(String appCode, String appPwd) {
		Response result = null;
		if (StringUtil.isNotNullNotEmpty(appCode) && StringUtil.isNotNullNotEmpty(appPwd)){
			try {
				String code = appConfig("GlobalConfig","appCode");
				if(code.equals(appCode)) {
					String isEncryptAppPwd = appConfig("GlobalConfig","isEncryptAppPwd");
					String pwd = appConfig("GlobalConfig","appPwd");
					
					if("Y".equals(isEncryptAppPwd)) {
						String privateKey = appConfig("GlobalConfig","privateKey");
						appPwd = appPwd.replace("encrypt-", "");
						appPwd = CryptionUtil.decryptByPrivateKey(new String(Base64.decodeBase64(appPwd.getBytes())), privateKey);
					}
					
					DataRow row = new DataRow("SYSINFO_PWD",pwd);
					
					result = buildTokenId(appCode, appPwd, row);
				}else {
					result = Response.status(Status.BAD_REQUEST).entity("app code is not encryption").build();
				}
			} catch (Exception e) {
				result = Response.status(Status.BAD_REQUEST).entity("app pwd is not encryption").build();
				e.printStackTrace();
			}
		}else{
			result = Response.status(Status.BAD_REQUEST).entity("param is not valid").build();
		}
		return result;
	}
	
	private String appConfig(String section,String entryCode) {
    	BeanFactory beanFactory = BeanFactory.instance();
		AppConfig appConfig = beanFactory.getAppConfig();
    	return appConfig.getConfig(section,entryCode);
    }
	
	
	private Response buildTokenId(String appCode,String appPwd,DataRow row){
		Response result = null;
		if (row!=null){
			appPwd = this.toEncryptionPwd(appPwd, appCode);
			String sysinfoPwdTemp = row.getString("SYSINFO_PWD");
			if (StringUtil.isNotNullNotEmpty(sysinfoPwdTemp)){
				if (appPwd.equals(sysinfoPwdTemp)){
					String tokenId = KeyGenerator.instance().genKey();
					Token token = new Token();
					token.setId(tokenId);
					token.setCode(appCode);
					token.setCreateTime(new Date());
					int maxAliveSeconds = 60*5;
					token.setMaxAliveSeconds(maxAliveSeconds);
					getCacheService().putValue(tokenId,token);
					result = Response.ok(tokenId).build(); 
				}else{
					result = Response.status(Status.BAD_REQUEST).entity("app pwd is not matched").build();
				}
			}else{
				result = Response.status(Status.BAD_REQUEST).entity("app pwd is not valid").build();	
			}
		}else{
			result = Response.status(Status.BAD_REQUEST).entity("record is not found").build();
		}
		return result;
    }
	
	private String toEncryptionPwd(String sysinfoPwd, String sysinfoCode){
    	String enpwd = "";
		String enKey = "";
		StringBuffer code = new StringBuffer(sysinfoCode); 
    	if(code.length()>=8){
    		enKey = sysinfoCode.substring(0, 8);
    	}
    	else{
    		while(code.length()<8){
    			code = code.append("x");
    		}
    		enKey = code.toString();
    	}
    	enpwd = CryptionUtil.encryption(sysinfoPwd, enKey);
		return enpwd;
    }
	
	public CacheService getCacheService(){
		CacheService result = (CacheService)BeanFactory.instance().getCacheService();
		return result;
	}
}
